package com.ruoyi.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.DataListStatusType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.data.domain.DataList;
import com.ruoyi.data.domain.HomeColConfig;
import com.ruoyi.data.domain.bo.DataClassificationBo;
import com.ruoyi.data.domain.vo.DataClassificationVo;
import com.ruoyi.data.domain.vo.HomeColConfigVo;
import com.ruoyi.data.domain.vo.IndexStatisticsVo;
import com.ruoyi.data.mapper.DataClassificationMapper;
import com.ruoyi.data.mapper.DataListMapper;
import com.ruoyi.data.mapper.HomeColConfigMapper;
import com.ruoyi.data.service.IIndexService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页统计
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@RequiredArgsConstructor
@Service
public class IndexServiceImpl implements IIndexService {

    private final DataListMapper dataListMapper;
    private final DataClassificationMapper dataClassificationMapper;
    private final SysUserMapper sysUserMapper;
    private final HomeColConfigMapper homeColConfigMapper;



    @Override
    public List <IndexStatisticsVo> getIndexStatistics() {
        RedissonClient client = RedisUtils.getClient();

        List <IndexStatisticsVo> list = new ArrayList<>();


        Long userId = LoginHelper.isAdmin()? null : LoginHelper.getUserId();

        List<DataClassificationVo> dataClassificationVos = dataClassificationMapper.selectClassificationByIdUserId(userId, new DataClassificationBo());

        dataClassificationVos.forEach(d -> {

            //查询已读数量
            LambdaQueryWrapper<DataList> readCountLqw = Wrappers.lambdaQuery();
            readCountLqw.eq(DataList::getClassificationId, d.getClassificationId());
            readCountLqw.eq(DataList::getStatus, DataListStatusType.READ.getClassificationType());
            readCountLqw.eq( DataList::getUserId, d.getUserId());

            //未读数量
            LambdaQueryWrapper<DataList> notReadCountLqw = Wrappers.lambdaQuery();
            notReadCountLqw.eq(DataList::getClassificationId, d.getClassificationId());
            notReadCountLqw.eq(DataList::getStatus, DataListStatusType.NOT_READ.getClassificationType());
            notReadCountLqw.eq( DataList::getUserId, d.getUserId());

            //实时 已缓存 数量
            String KEY = CacheConstants.ONE_DATA_KEY + d.getUserId() + ":" + d.getClassificationId();
            RScoredSortedSet<String> sortedSet = client.getScoredSortedSet(KEY);

            list.add(IndexStatisticsVo
                .builder()
                    .userId(d.getUserId())
                    .classificationId(d.getClassificationId())
                    .title(d.getClassificationName())
                    .readCount(dataListMapper.selectCount(readCountLqw))
                    .notReadCount(dataListMapper.selectCount(notReadCountLqw))
                    .redisReadCount(sortedSet.size())
                    .redisKey(KEY)
                .build());
        });


        return list;
    }

    @Override
    @Transactional
    public String setPageJson(HomeColConfigVo homeColConfigVo) {
        homeColConfigMapper.deleteById(LoginHelper.getUserId());
        homeColConfigMapper.insert(HomeColConfig.builder().classificationId(homeColConfigVo.getClassificationId()).status(homeColConfigVo.getStatus()).userId(LoginHelper.getUserId()).json(homeColConfigVo.getJson()).build());
        return "success";
    }

    @Override
    public String getPageJson(HomeColConfig req) {
        if (req == null) return "";

        HomeColConfig homeColConfig = homeColConfigMapper.selectOne(new LambdaQueryWrapper<HomeColConfig>()
            .eq(req.getClassificationId() != null, HomeColConfig::getClassificationId, req.getClassificationId())
            .eq(StringUtils.isNotEmpty(req.getStatus()), HomeColConfig::getStatus, req.getStatus())
            .eq(HomeColConfig::getUserId, LoginHelper.getUserId()));

        if (homeColConfig == null) return null;
        return homeColConfig.getJson();
    }
}
